package cn.hzking.gjmall.activitys.second;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fingdo.statelayout.StateLayout;
import com.mikhaellopez.circularimageview.CircularImageView;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.adpters.nyuan.NYuanAdapter;
import cn.hzking.gjmall.app.Gjmall;
import cn.hzking.gjmall.base.ColorStatuBarActivity;
import cn.hzking.gjmall.bean.NYuanBean;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.GjCustomStateViewObserver;
import cn.hzking.gjmall.utils.SwipeRefreshLayoutUtils;
import cn.hzking.gjmall.view.SimpleOptionView;

/**
 * N元选列表
 */
public class NYuanGoodListActivity extends ColorStatuBarActivity {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.refrsh)
    SwipeRefreshLayout refrsh;
    @Bind(R.id.statlayout)
    StateLayout statlayout;
    private NYuanAdapter nYuanAdapter;
    @Bind(R.id.nyrl)
    RelativeLayout ryRl;
    @Bind(R.id.nycarimage)
    ImageView carImage;
    @Bind(R.id.unread_num)
    TextView tvunNum;
    @Bind(R.id.rl_car)
    RelativeLayout rlAddCar;
    private float[] mCurrentPosition = new float[2];
    private String imageUrl;//加入购物车图片的地址
    private Bitmap bitmap;
    private int carNum = 0;
    private PathMeasure mPathMeasure;
    private String nsId;
    private int currentPage = 1;
    private ImageView headImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_nyuan_good_list);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        simpleTileView.setTitle("N元选");
        Intent intent = getIntent();
        nsId = intent.getStringExtra("nsId");
        nsId = String.valueOf(128);
        initView();
        getNetData(nsId, true, false, true, true, null, null, null);
        initListener();
    }

    public void getNetData(final String nsId, final boolean isFristInit, boolean isRefrsh, boolean isShowDialog, boolean isCancel, View emptyView, View onNetView, View errorView) {
        RetrofitFactory.getInstant().API()
                .getNYuanList(nsId)
                .compose(this.<NYuanBean>setThread())
                .subscribe(new GjCustomStateViewObserver<NYuanBean>(this, statlayout,
                        refrsh, isFristInit, isRefrsh, isShowDialog, isCancel, emptyView, onNetView, errorView) {
                    @Override
                    protected void onBusinessSuccess(NYuanBean nYuanBean) throws Exception {
                        rlAddCar.setVisibility(View.VISIBLE);
                        if (nYuanBean != null) {
                            List<NYuanBean.DataBean.ActSkuListBean> itemList = nYuanBean.getData().getActSkuList();
                            if (currentPage == 1) {
                                nYuanAdapter.setNewData(itemList);
                                if(isFristInit) {
                                    View view = View.inflate(mContext, R.layout.item_nyuan_head, null);
                                    headImage = view.findViewById(R.id.head_image);
                                    nYuanAdapter.addHeaderView(view, 0);
                                    Glide.with(mContext).load(Gjmall.getOssHost() + nYuanBean.getData().getActivity().getImgUrl()).placeholder(R.mipmap.xiangqing).error(R.mipmap.xiangqing).into(headImage);
                                }
                                if (nYuanAdapter.getData().size() == 0) {
                                    View view = View.inflate(mActivity,R.layout.layout_statelayout_custom_goodlist_empty,null);
                                    statlayout.showCustomView(view);
                                    rlAddCar.setVisibility(View.INVISIBLE);
                                    return;
                                }
                            } else {
                                nYuanAdapter.addData(itemList);
                            }

                            currentPage++;
                        }
                        int itemCount = nYuanAdapter.getData().size();
                       /* if (nYuanBean.getData().getTotalRecord() == itemCount) {//数据加载完成
                            cateGoryGoodListAdapter.loadMoreEnd(true);

                        } else {
                            cateGoryGoodListAdapter.loadMoreComplete();
                        }*/

                    }

                    @Override
                    protected void onChildFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        rlAddCar.setVisibility(View.INVISIBLE);
                    }


                });
    }

    private void initView() {
        SwipeRefreshLayoutUtils.initRefreshLayout(refrsh);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
        recyclerview.setLayoutManager(gridLayoutManager);
        nYuanAdapter = new NYuanAdapter(R.layout.item_nyuan_goodlist, null);
        nYuanAdapter.setNyId(nsId);
        recyclerview.setAdapter(nYuanAdapter);
        nYuanAdapter.setAddCarListener(new NYuanAdapter.AddCarListener() {
            @Override
            public void onAdd(ImageView imageView, ImageView showImage) {
                measureView(imageView, showImage);
            }
        });

    }

    private void initListener() {
        //加载更多
        nYuanAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                getNetData(nsId, false, false, false, false, null, null, null);
            }
        }, recyclerview);

        //刷新
        refrsh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData(nsId, false, true, false, false, null, null, null);
            }
        });


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    private void measureView(ImageView resource, ImageView showImage) {
        //      一、创造出执行动画的主题---imageview
        //代码new一个imageview，图片资源是上面的imageview的图片
        // (这个图片就是执行动画的图片，从开始位置出发，经过一个抛物线（贝塞尔曲线），移动到购物车里)
        final CircularImageView goods = new CircularImageView(NYuanGoodListActivity.this);
        goods.setBorderWidth(0);
        Drawable drawable = showImage.getDrawable();
        goods.setImageDrawable(drawable);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
        ryRl.addView(goods, params);

//        二、计算动画开始/结束点的坐标的准备工作
        //得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
        int[] parentLocation = new int[2];
        ryRl.getLocationInWindow(parentLocation);

        //得到商品图片的坐标（用于计算动画开始的坐标）
        int startLoc[] = new int[2];
        resource.getLocationInWindow(startLoc);

        //得到购物车图片的坐标(用于计算动画结束后的坐标)
        int endLoc[] = new int[2];
        carImage.getLocationInWindow(endLoc);


//        三、正式开始计算动画开始/结束的坐标
        //开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
        float startX = startLoc[0] - parentLocation[0] + resource.getWidth() / 2;
        float startY = startLoc[1] - parentLocation[1] + resource.getHeight() / 2;

        //商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
        float toX = endLoc[0] - parentLocation[0] + carImage.getWidth() / 5;
        float toY = endLoc[1] - parentLocation[1];

//        四、计算中间动画的插值坐标（贝塞尔曲线）（其实就是用贝塞尔曲线来完成起终点的过程）
        //开始绘制贝塞尔曲线
        Path path = new Path();
        //移动到起始点（贝塞尔曲线的起点）
        path.moveTo(startX, startY);
        //使用二次萨贝尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        //mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，
        // 如果是true，path会形成一个闭环
        mPathMeasure = new PathMeasure(path, false);

        //★★★属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(500);
        // 匀速线性插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 当插值计算进行时，获取中间的每个值，
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // ★★★★★获取当前点坐标封装到mCurrentPosition
                // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距
                // 离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                mPathMeasure.getPosTan(value, mCurrentPosition, null);//mCurrentPosition此时就是中间距离点的坐标值
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
//      五、 开始执行动画
        valueAnimator.start();

//      六、动画结束后的处理
        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                Log.e("hh", "开始");

            }

            //当动画结束后：
            @Override
            public void onAnimationEnd(Animator animation) {
                Log.e("hh", "结束");
                carNum++;
                if (carNum > 0) {
                    tvunNum.setVisibility(View.VISIBLE);
                    tvunNum.setText(String.valueOf(carNum));
                    ryRl.removeView(goods);//把imageview移除
                }
              /*  // 购物车的数量加1
                i++;
                count.setText(String.valueOf(i));
                // 把移动的图片imageview从父布局里移除
                */

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }
}
